from rest_framework.serializers import ModelSerializer, SerializerMethodField
from rest_framework import serializers

from community.models import *
from user import views


class ArticleSerializer(ModelSerializer):
    class Meta:
        model = Article
        exclude = ['is_delete']


class CommentSerializer(ModelSerializer):
    user_name = serializers.CharField(source='user.first_name', read_only=True)  # 评论者name
    user_avatar = serializers.CharField(source='user.userdetail.avatar', read_only=True)  # 头像
    reply_name = SerializerMethodField()  # 方法字段,它可以去调用某一个方法

    class Meta:
        model = Comment
        fields = "__all__"

    def get_reply_name(self, comment):
        try:
            user = Comment.objects.get(id=comment.reply_comment).user  # 拿到id=2的回复者id
            reply_name = user.first_name
        except:
            reply_name = None  # 因为回复者有可能回复的是文章
        return reply_name  # 回复者的first_name


class CommentHandlerSerializer(ModelSerializer):
    # 存放所有level=2的字段
    son_comment = SerializerMethodField()  # 方法字段,它可以去调用某一个方法,如：get_son_comment(),方法名固定
    user_name = serializers.CharField(source='user.first_name', read_only=True)  # 评论者name
    user_avatar = serializers.CharField(source='user.userdetail.avatar', read_only=True)  # 头像

    class Meta:
        model = Comment
        fields = "__all__"

    def get_son_comment(self, comment):
        # 查询所有parent_comment为level为1的评论的id的评论  # 拿到评论者的id(1)
        serializer = CommentSerializer(Comment.objects.filter(parent_comment=comment.id), many=True)
        data = serializer.data
        data.reverse()
        return data
